//
//  TravelDetailController.m
//  XhlTrip
//
//  Created by dllo on 15/8/22.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "TravelDetailController.h"
#import "TravelDetailCell.h"
#import "LeaonWorking.h"
#import "TraDetaHeaView.h"
#import "TravelModel.h"
#import "UIImageView+WebCache.h"
#import "DataBase.h"
#import "DBModel.h"
#import "MBProgressHUD.h"

@interface TravelDetailController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) NSMutableDictionary *travelDic;
@property (nonatomic, retain) NSMutableArray *travelDayArr;
@property (nonatomic, retain) UITableView *tableViewDetil;
@property (nonatomic, retain) TraDetaHeaView *headerView;


@end

@implementation TravelDetailController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
       
        
       
        self.travelDayArr = [NSMutableArray array];
    }
    return self;
}


/* 网络请求 第一页创建此页对象 就调用了这个方法 并传过来id号 */
- (void)passDetailValue:(NSString *)idStr
{
    
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:hud];
    hud.labelText = @"正在加载";
    [hud show:YES];
    
        NSString *path = [NSString stringWithFormat:@"%@%@%@",@"https://chanyouji.com/api/trips/", idStr, @".json"];
    NSString *nn = [NSString stringWithFormat:@"%@%@", @"travel", idStr];
        [LeaonWorking netWorkingHanderGetGataWithUrl:path pathname:nn resultBlock:^(id result) {
            self.travelDic  = result;
            [self.travelDayArr addObjectsFromArray:[self.travelDic objectForKey:@"trip_days"]];
            [self createHeaderView];
            [self.headerView.SmallImageView sd_setImageWithURL:[[self.travelDic objectForKey:@"user"] objectForKey:@"image"]];
            
                        [self createSaveButton];
#pragma mark - 数据请求之后tableview重新加载数据
            [_tableViewDetil reloadData];
            /* 数据传过来之后 */
            [self myTask];
            [hud removeFromSuperview];
            [hud release];

        }];
    


}
- (void)myTask {
    // Do something usefull in here instead of sleeping ...
    sleep(10);
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self createTableView];
   
    
  
}

/* 创建tableView */
- (void)createTableView
{
    self.tableViewDetil = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    self.tableViewDetil.dataSource = self;
    self.tableViewDetil.delegate = self;
    [self.view addSubview:self.tableViewDetil];
    _tableViewDetil.separatorColor = [UIColor grayColor];
    _tableViewDetil.rowHeight = 200;
#pragma mark - 创建headerView
    self.headerView = [[[TraDetaHeaView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200 * Height)]autorelease];
   

    self.tableViewDetil.tableHeaderView = self.headerView;
    [_tableViewDetil release];
    _tableViewDetil.backgroundColor = [UIColor whiteColor];
    
}

- (void)createHeaderView
{
    TravelModel *model = [[TravelModel alloc] init];
    [model setValuesForKeysWithDictionary:self.travelDic];
    self.headerView.travelModel = model;
}

/* 分区数 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.travelDayArr.count;
}


/* 行数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  
    NSArray *cellArr = [self returnArrayThatYouNeed:[self.travelDayArr[section] objectForKey:@"nodes"]];
    return cellArr.count;
}

/* 整理数据 */

- (NSMutableArray *)returnArrayThatYouNeed:(NSMutableArray *)nodes {
    NSMutableArray *newArray = [NSMutableArray array];
    for (NSDictionary *nodeDic in nodes) {
        NSMutableArray *notes = [NSMutableArray array];
        notes = [nodeDic objectForKey:@"notes"];
        for (NSDictionary *noteDic in notes) {
            [newArray addObject:noteDic];
        }
    }
    return newArray;
}


/* 创建cell */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"ss";
    TravelDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    
    if (cell == nil) {
        cell = [[[TravelDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
    }
    /* 从重用池去除视图并清除上面的子视图 */
    while ([cell.contentView.subviews lastObject] != nil) {
        [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];  //删除并进行重新分配
    }
   

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray *a = [self returnArrayThatYouNeed:[self.travelDayArr[indexPath.section] objectForKey:@"nodes"]];
    [cell passValue:[a objectAtIndex:indexPath.row]];

    
    
    return cell;
}

/* cell 高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

 
    NSArray *a = [self returnArrayThatYouNeed:[self.travelDayArr[indexPath.section] objectForKey:@"nodes"]];
 
    CGFloat textHeight;
    CGFloat photoHeight;
    if ([a[indexPath.row] objectForKey:@"photo"]) {
        photoHeight = [TravelDetailCell heightWithImage:[a[indexPath.row] objectForKey:@"photo"] width:self.view.frame.size.width - 20];
    }else
    {
        photoHeight = 0;
    }

    if ([[[a objectAtIndex:indexPath.row] objectForKey:@"description"] isKindOfClass:[NSNull class]]) {
    }else{
    
        textHeight = [TravelDetailCell heightWithText:[a[indexPath.row] objectForKey:@"description"] width:self.view.frame.size.width - 20];
    }
    return textHeight + photoHeight + 40 * Height;
      
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSNumber *num = [[self.travelDayArr objectAtIndex:section] objectForKey:@"day"];
    NSString *ff = [NSString stringWithFormat:@"%@%@",  @"DAY", num];
    return ff;
}

/* 收藏按钮 */
- (void)createSaveButton
{
   
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 30 * Width, 30 * Height);
        [button addTarget:self action:@selector(shoucangButton:) forControlEvents:UIControlEventTouchUpInside];
        NSString *ss = [NSString stringWithFormat:@"%@", [self.travelDic objectForKey:@"id"]];
    
        if ([DataBase selectoneWith:ss] != nil) {
            [button setBackgroundImage:[self nameWithPath:@"shoucangS.png"] forState:UIControlStateNormal];
        }else{
            [button setBackgroundImage:[self nameWithPath:@"shoucang.png"] forState:UIControlStateNormal];
        }
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
       
}

/* 收藏点击事件 */
- (void)shoucangButton:(UIButton *)button
{
    
    NSString *ss = [NSString stringWithFormat:@"%@", [self.travelDic objectForKey:@"id"]];
    
    if ([DataBase selectoneWith:ss] != nil)  {
        [button setBackgroundImage:[UIImage imageNamed:@"shoucang.png"] forState:UIControlStateNormal];
        
        DBModel *model = [DBModel dbModelWith:[self.travelDic objectForKey:@"name"] photos_count:[self.travelDic objectForKey:@"photos_count"] start_date:[self.travelDic objectForKey:@"start_date"] days:[self.travelDic objectForKey:@"days"] front_cover_photo_url:[self.travelDic objectForKey:@"front_cover_photo_url"] number:[self.travelDic objectForKey:@"id"]];
        [DataBase deleteWithModel:model];
    }else
    {
        [button setBackgroundImage:[UIImage imageNamed:@"shoucangS.png"] forState:UIControlStateNormal];
        
        DBModel *model = [DBModel dbModelWith:[self.travelDic objectForKey:@"name"] photos_count:[self.travelDic objectForKey:@"photos_count"] start_date:[self.travelDic objectForKey:@"start_date"] days:[self.travelDic objectForKey:@"days"] front_cover_photo_url:[self.travelDic objectForKey:@"front_cover_photo_url"] number:[self.travelDic objectForKey:@"id"]];
        [DataBase insertWithModel:model];
    }
}

- (UIImage *)nameWithPath:(NSString *)paths
{
    NSString *path = [[NSBundle mainBundle] pathForResource:paths ofType:nil];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    return image;
}




- (void)dealloc
{
    
    [_headerView release];
    [_tableViewDetil release];
    [_travelDayArr release];
    [_travelDic release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
   
    self.tabBarController.tabBar.hidden = YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
